﻿using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Mono.Cecil;

namespace NotifyPropertyWeaverMsBuildTask
{
    [Export, PartCreationPolicy(CreationPolicy.Shared)]
    public class OnChangedWalker
    {
        TypeNodeBuilder typeNodeBuilder;

        [ImportingConstructor]
        public OnChangedWalker(TypeNodeBuilder typeNodeBuilder)
        {
            this.typeNodeBuilder = typeNodeBuilder;
        }

        public void Execute()
        {
            Process(typeNodeBuilder.NotifyNodes);
        }

        void Process(List<TypeNode> notifyNodes)
        {
            foreach (var notifyNode in notifyNodes)
            {
                notifyNode.OnChangedMethods = GetOnChangedMethods(notifyNode).ToList();
                Process(notifyNode.Nodes);
            }
        }

        private static IEnumerable<MethodDefinition> GetOnChangedMethods(TypeNode notifyNode)
        {
            var methods = notifyNode.TypeDefinition.Methods;
            return methods.Where(methodDefinition => !methodDefinition.IsStatic &&
                                                     !methodDefinition.IsAbstract && 
                                                     methodDefinition.Parameters.Count == 0 &&
                                                     methodDefinition.Name.StartsWith("On") &&
                                                     methodDefinition.Name.EndsWith("Changed"));
        }
    }
}